using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace WindowsUserControl.UIUpdateWrapper
{
    /// <summary>
    /// 
    /// </summary>
    public class  DataGridViewUpdator
    {
        private DataGridView _DV;
        private DataGridViewRow[] _Rows;
        private DataTable _Data;
        private bool _IsNew;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dv"></param>
        /// <param name="rows"></param>
        /// <param name="isNew"></param>
        public DataGridViewUpdator(DataGridView dv, DataGridViewRow[] rows, bool isNew)
        {
            this._DV = dv;
            this._Rows = rows;
            this._IsNew = isNew;
            if (this._IsNew)
            {
                this._DV.Invoke(new MethodInvoker(this.AddDataGrieViewRow));
            }
            else
            {
                this._DV.Invoke(new MethodInvoker(this.RefreshDataGridView));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dv"></param>
        /// <param name="dt"></param>
        public DataGridViewUpdator(DataGridView dv, DataTable dt)
        {
            this._DV = dv;
            this._Data = dt;
            this._DV.Invoke(new MethodInvoker(this.RefreshDataGridView));
        }

        private void RefreshDataGridView()
        {
            if(this._Data !=null)
            {
                this._DV.DataSource = this._Data;
            }
            else if(this._Rows !=null && this._Rows.Length>0)
            {
                this._DV.Rows.Clear();
                for(int i=0;i<this._Rows.Length;i++)
                {
                    this._DV.Rows.Add(this._Rows[i]);
                }
            }
            this._DV.Refresh();
        }

        private void AddDataGrieViewRow()
        {
            if (this._Rows != null && this._Rows.Length > 0)
            {
                for (int i = 0; i < this._Rows.Length; i++)
                {
                    this._DV.Rows.Add(this._Rows[i]);
                }
            }
            this._DV.Refresh();
        }
    }
}
